<template>
  <div class="order-container">
    <div v-if="chosenAddressId===null" class="van-contact-card van-contact-card--add" @click="showAddressList = true">
      <div class="van-contact-card__content">
        <i class="van-icon van-icon-add2 van-contact-card__icon"></i>
        <div class="van-contact-card__text">请选择一个收货地址</div>
      </div>
      <i class="van-icon van-icon-arrow van-contact-card__arrow"></i>
    </div>

    <div v-if="chosenAddressId!==null" class="order-address van-contact-card van-contact-card--edit" @click="showAddressList = true">
      <div class="van-contact-card__content">
        <div class="van-contact-card__text">
          <div>地址：{{ currentAddress.address }}</div>
          <div>姓名：{{ currentAddress.name }}</div>
          <div>手机：{{ currentAddress.tel }}</div>
        </div>
      </div>
      <i class="van-icon van-icon-arrow van-contact-card__arrow"></i>
    </div>

    <div class="van-card" v-for="p in products">
      <div class="van-card__thumb">
        <img v-if="JSON.parse(p.images)[0]" :alt="p.name" :src="config.uploadUrl+JSON.parse(p.images)[0]" class="van-card__img"/>
        <img v-if="!JSON.parse(p.images)[0]" :alt="p.name" :src="'http://iph.href.lu/100x100?text=%E6%97%A0%E5%9B%BE%E7%89%87'" class="van-card__img"/>
      </div>
      <div class="van-card__content">
        <div class="van-card__row">
          <div class="van-card__title">{{ p.name }}</div>
          <div class="van-card__price">
            <div v-if="p.price_rmb > 0">¥:{{ Math.round(p.price_rmb,2) }}</div>
            <div v-if="p.price_retail > 0" class="van-card__price">零售积分:{{ Math.round(p.price_retail,2) }}</div>
            <div v-if="p.price_shop > 0" class="van-card__price">商城积分:{{ Math.round(p.price_shop,2) }}</div>
          </div>
        </div>
        <div class="van-card__row">
          <!--<div class="van-card__desc">描述信息</div>-->
          <div class="van-card__num">x {{ p.amount }}</div>
        </div>
      </div>
    </div>

    <van-popup class="order-address-list" v-model="showAddressList" position="top" :overlay="false">
      <van-address-list
        v-model="chosenAddressId"
        :list="addressList"
        @add="onAddressListAdd"
        @select="onAddressListSelect"
      />
    </van-popup>

    <van-dialog
      v-model="showDialog"
      show-cancel-button
      @confirm="confirmDialog"
    >
      <div class="van-cell van-cell--required van-hairline van-field" :class="{'van-cell--center van-field--error': errors.has('safePassword')}">
        <div class="van-cell__title"><span>安全密码</span></div>
        <div class="van-cell__value">
          <input v-model="formFields.safePassword" v-validate="'required|min:6'" name="safePassword" type="password" placeholder="请输入安全密码" class="van-field__control">
          <div v-if="errors.has('safePassword')" class="van-field__error-message">{{ errors.first('safePassword') }}</div>
        </div>
      </div>
    </van-dialog>

    <van-submit-bar
      button-text="提交订单"
      @submit="onSubmitOrder"
    />
  </div>
</template>

<script>
import qs from 'qs';
import Vue from 'vue';
import { ContactCard, Popup, AddressList, Card, SubmitBar, Field, Toast, Dialog } from 'vant';
import ajaxVant from '../../../utils/ajaxVant';
import auth from '../../../utils/auth';
import areaList from '../../../mock/area';
import config from '../../../config';

Vue.use(Dialog);

export default {
  components: {
    [ContactCard.name]: ContactCard,
    [Popup.name]: Popup,
    [AddressList.name]: AddressList,
    [Card.name]: Card,
    [SubmitBar.name]: SubmitBar,
    [Field.name]: Field
  },
  data() {
    return {
      areaList,
      config,
      showDialog: false,
      showAddressList: false,
      chosenAddressId: null,
      currentAddress: {},
      addressList: [],
      products: [],
      formFields: {
        addressId: null,
        safePassword: '',
        products: {}
      }
    };
  },
  methods: {
    onSubmitOrder: function() {
      var _this = this;
      if (_this.formFields.addressId === null) {
        Toast('请选择地址!');
        return false;
      }

      _this.showDialog = true;
    },
    confirmDialog() {
      var _this = this;
      _this.showDialog = true;
      _this.$validator.validateAll().then((result) => {
        if (result) {
          auth.getToken().then(function(token) {
            ajaxVant.post('/user/order?token=' + token, qs.stringify(_this.formFields)).then(function(data) {
              if (data !== false) {
                Toast(data.msg);

                setTimeout(() => {
                  Toast.clear();
                  _this.$router.push({ name: 'userOrder' });
                }, 1000);
              }

              _this.safePassword = '';
            });
          });

          _this.showDialog = false;
        }
      });
    },
    onAddressListAdd() {
      this.$router.push({ name: 'userAddressCreate' });
    },
    onAddressListSelect(item, index) {
      this.showAddressList = false;
      this.currentAddress = item;
      this.chosenAddressId = item.id;
      this.formFields.addressId = this.chosenAddressId;
    },
    getAddressData() {
      var _this = this;
      auth.getToken().then(function(token) {
        ajaxVant.get('/user/address?token=' + token).then(function(data) {
          if (data !== false) {
            for (var i in data.pager) {
              let address = areaList['province_list'][data.pager[i].area_code.substring(0, 2) + '0000'];
              address += areaList['city_list'][data.pager[i].area_code.substring(0, 4) + '00'];
              address += areaList['county_list'][data.pager[i].area_code];
              address += data.pager[i].address_detail;
              _this.addressList.push({
                id: data.pager[i].address_id,
                name: data.pager[i].name,
                tel: data.pager[i].tel,
                address: address
              });

              if (data.pager[i].is_default.toString() === '1') {
                _this.chosenAddressId = data.pager[i].address_id;
                _this.formFields.addressId = _this.chosenAddressId;
                _this.currentAddress = data.pager[i];
                _this.currentAddress.address = address;
              }
            }
          }
        });
      });
    },
    getProductsData() {
      var _this = this;
      var products = qs.parse(_this.$route.query.products);
      var ids = [];
      for (var id in products) {
        ids.push(id);
      }

      ajaxVant.get('/products/findByIds?' + qs.stringify({ ids: ids })).then(function(data) {
        if (data !== false) {
          for (const i in data.pager) {
            data.pager[i].amount = products[data.pager[i].products_id].amount;
            _this.products.push(data.pager[i]);
            _this.formFields.products[data.pager[i].products_id] = { amount: products[data.pager[i].products_id].amount };
          }
        }
      });
    }
  },
  mounted() {
    this.getAddressData();
    this.getProductsData();
  }
};

</script>

<style>
.order-container {
  padding-bottom: 100px;
}
.order-container .order-address.van-contact-card {
  width: 100%;
  overflow:hidden;
}
.order-container .order-address.van-contact-card .van-contact-card__text {
  width: 100%;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}
.order-address-list {
  height: 100%;
}
.order-container .van-card__price {
  color: #f44;
}
</style>
